package com.fengmi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fengmi.entity.SysUser;
import com.fengmi.entity.ViewUserRolePermission;
import com.fengmi.mapper.UserMapper;
import com.fengmi.service.IUserService;
import com.fengmi.utils.security.JwtUtils;
import com.fengmi.utils.security.RsaUtils;
import com.fengmi.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.security.PrivateKey;
import java.util.List;

/**
 * 作者：陈学虎
 * 时间：2021/7/14 0014 上午 9:18
 */
@Service
@Transactional
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVO login(SysUser sysUser) {
        try {
            if (sysUser == null){
                return new ResultVO(false,"请求参数错误");
            }

            //根据用户名获取用户的角色  权限  等信息
             SysUser user = userMapper.findByAccount(sysUser.getAccount());
            if (user == null){
                return new ResultVO(false,"用户不存在");
            }

            //获取用户的角色信息
            List<String> role = userMapper.findRole(sysUser.getAccount());
            String roles = StrUtil.join(",", role);
            user.setRole(roles);

            //获取用户的权限信息
            List<String> permission = userMapper.findPermission(sysUser.getAccount());
            String permissions = StrUtil.join(",", permission);
            user.setPermission(permissions);

            //校验密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            if (!encoder.matches(sysUser.getPassword(),user.getPassword())){
                return new ResultVO(false,"用户名或密码错误!");
            }

            //将密码置空
            user.setPassword(null);

            //颁发令牌 加载私钥
            String path = ResourceUtils.getFile("classpath:rsa").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(path);
            String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 30);

            return new ResultVO(true,"success",token);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false,"登录失败");
        }
    }
}
